package com.ff.javamonkey.ui;

import java.io.File;
import java.io.IOException;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.ff.javamonkey.R;
import com.ff.javamonkey.sqlite.ACRLDbAdapter;
import com.ff.javamonkey.sqlite.SingletonDb;
import com.ff.javamonkey.sqlite.SqliteExporter;
import com.ff.javamonkey.sqlite.type.AcrlacDb;
import com.ff.javamonkey.sqlite.type.Group;
import com.ff.javamonkey.ui.adapter.AcrldbListAdapter;

public class ACRLListActivity extends ListActivity {
	// Debugging
	private static final String TAG = "ACRLListActivity";
	
	// UI Components
	private ListView mListView;
	private AcrldbListAdapter mListAdapter;
	
	// DB Stuff
	private SqliteExporter sqliteExporter;
	private ACRLDbAdapter mACRLDbAdapter;
	
	public static String FILE_PATH = "file";
	private String[] importedFile;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acrl_list);
		
		// Prepare the UIs
		mListView = getListView();
		mListAdapter = new AcrldbListAdapter(this);
		
		if (getIntent().getExtras() != null) {
			importedFile = getIntent().getExtras().getStringArray(FILE_PATH);
		}
		
		// Let's export SQLite files
		sqliteExporter = new SqliteExporter(this.getApplicationContext());
		
		// Setup for displays
		Group<AcrlacDb> group = new Group<AcrlacDb>();
		
		for (String s : importedFile) {
			File dbFile = new File(Environment.getExternalStorageDirectory(), "ff/"+s);
			//Log.i(TAG, dbFile.toString());// cool, full path
			try {
				sqliteExporter.copyDatabase(dbFile, s);
			} catch (IOException e) {
				e.printStackTrace();
			}
			// for every database, read its row size, display.
			mACRLDbAdapter = SingletonDb.getDb(this, s).getACRLDbAdapter();
			Log.i(TAG, "Database file : " +s);
			Cursor c = mACRLDbAdapter.fetchAll();
			startManagingCursor(c);
			int rows = c.getCount();
			c.close();
			Log.i(TAG, s + " contents " + rows);
			AcrlacDb a = new AcrlacDb();
			a.setmContent(rows);
			a.setmFileName(s);
			group.add(a);
			SingletonDb.close();
		}
		
		updateList(group);
	}
	
	private void updateList(Group<AcrlacDb> value) {
		mListAdapter.setGroup(value);
		setListAdapter(mListAdapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int positionl, long id) {
		AcrlacDb adb = (AcrlacDb)l.getAdapter().getItem(positionl);
		Intent intent = new Intent(this, ACRLTransferActivity.class);
		intent.putExtra(ACRLTransferActivity.FILE_PATH, adb.getmFileName());
		startActivity(intent);
	}
}
